package com.yunchi.service.impl;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpUtil;
import com.yunchi.service.MonitorService;
import com.yunchi.utils.FileUtils;
import com.yunchi.utils.MonitorPropertiesUtils;
import com.yunchi.utils.SMSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import javax.xml.xpath.XPathConstants;
import java.io.IOException;

/**
 * @Author: Crazer
 * @Date: 2023/7/4 10:56
 * @version: 1.0.0
 * @Description:
 */
@Service
public class MonitorServiceImpl implements MonitorService {

    private static final Logger logger = LoggerFactory.getLogger(MonitorServiceImpl.class);

    @Override
    public boolean monitor() {
        String xmlData = "";
        try {
            xmlData = FileUtils.readFileAsString(MonitorPropertiesUtils.XMLDATA);
        } catch (IOException e) {
            logger.error("读取本地xml数据失败，异常原因：\n", e);
            sendErrorMessage("读取本地xml数据失败");
            return false;
        }
        String resultXml = null;
        try {
            resultXml = HttpUtil.post(MonitorPropertiesUtils.URL, xmlData);
        } catch (Exception e) {
            logger.error("发送请求失败,请检查服务是否正常：{}，异常原因：\n", resultXml, e);
            sendErrorMessage("发送请求失败,请检查服务是否正常");
            return false;
        }
        logger.info("请求返回的报文为：\n{}", resultXml);
        // System.out.println(resultXml);
        /*
        <cslife>
        <csHeader>
            <retCode>0</retCode>
            <retMsg>请求pdf合成成功！</retMsg>
        </csHeader>
        <csContent>
        <resultCode>success</resultCode>
        <resultDecription>合成成功</resultDecription>
        <pdfpath>https://tstimage.gwcslife.com/printsource/PDF/preview/E4C76A1A0A52FBB6D7D4F3CDC1D04C62N.pdf</pdfpath>
        <specialpdfpath></specialpdfpath>
        </csContent>
        </cslife>
         */
        Object retCode = null;
        Object retMsg = null;
        try {
            Document docResult = XmlUtil.parseXml(resultXml);
            retCode = XmlUtil.getByXPath("//cslife/csHeader/retCode", docResult, XPathConstants.STRING);
            retMsg = XmlUtil.getByXPath("//cslife/csHeader/retMsg", docResult, XPathConstants.STRING);
        } catch (Exception e) {
            logger.error("解析返回结果失败：{}，异常原因：\n", resultXml, e);
            sendErrorMessage("解析返回结果失败");
            return false;
        }

        if ("0".equals(String.valueOf(retCode))) {
            return true;
        }
        sendErrorMessage("pdf合成失败原因为：" + retMsg);
        logger.error("pdf合成失败原因为：{}" + retMsg);
        return false;
    }

    /**
     * 出现错误，发送短信
     *
     * @param message 发送内容
     */
    private void sendErrorMessage(String message) {
        SMSUtils.sendSMS(MonitorPropertiesUtils.SMS_URL, MonitorPropertiesUtils.SMS_PHONE, message);
    }
}
